﻿using System;
using System.Windows.Media;
using Telerik.Windows.Documents.Fixed.Model.Editing;

namespace Com.Lancetinc.Evs.Reports.RadPdf;

internal static class TextRenderer
{
    public static void DrawTextBlock(string text, PdfRenderContext context, Brush foreground, double width,
        double height, FontFamily fontFamily, double fontSize)
    {
        if (string.IsNullOrEmpty(text))
            return;

        using (context.drawingSurface.SaveProperties())
        {
            UIElementRendererBase.SetFill(context, foreground, width, height);
            SetFontFamily(context.drawingSurface, fontFamily);
            context.drawingSurface.TextProperties.FontSize = fontSize;

            var block = new Block();
            block.TextProperties.CopyFrom(context.drawingSurface.TextProperties);
            block.GraphicProperties.CopyFrom(context.drawingSurface.GraphicProperties);
            var textLines = text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

            foreach (var textLine in textLines)
            {
                block.InsertText(textLine);
                block.InsertLineBreak();
            }

            context.drawingSurface.DrawBlock(block);
        }
    }

    private static void SetFontFamily(FixedContentEditor drawingSurface, FontFamily fontFamily)
    {
        if (!drawingSurface.TextProperties.TrySetFont(fontFamily))
        {
            throw new Exception("Unable to set font. Consider embedding the font.");
        }
    }
}